<script setup lang="ts">
import { loginAPI } from '@/api/login'
import { useUserStore } from '@/stores/counter'
import type { loginParams } from '@/types/login'
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import { ref } from 'vue'
import { useRouter } from 'vue-router'

const login = ref<loginParams>({
  mobile: '13200000000',
  code: '246810',
})

const loginForm = ref<FormInstance>()
const FormRules = ref<FormRules<loginParams>>({
  mobile: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3456789]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' },
  ],
  code: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    { pattern: /^\d{6}$/, message: '请输入6位数字验证码', trigger: 'blur' },
  ],
})

const store = useUserStore()
const router = useRouter()
// 登录提交
const onsubmit = () => {
  loginForm.value?.validate(async (res) => {
    if (res) {
      try {
        const res = await loginAPI(login.value)
        // console.log(res.data.token)
        store.setToken(res.data.token)
        router.push('/')
        ElMessage.success('登录成功')
      } catch {}
    } else {
      console.log('校验不通过')
    }
  })
}
</script>

<template>
  <div class="container">
    <el-card>
      <img src="../../assets/images/logo.png" alt="" class="ImageTODO" />
      <el-form :model="login" :rules="FormRules" ref="loginForm">
        <el-form-item prop="mobile">
          <el-input placeholder="请输入手机号" v-model="login.mobile"></el-input>
        </el-form-item>
        <el-form-item prop="code">
          <el-input placeholder="密码" type="password" v-model="login.code"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onsubmit">登录</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<style scoped>
.container {
  display: flex;
  justify-content: center;
  align-content: center;
  background-image: url('../../assets/images/login.png');
  height: 100vh;
  background-size: cover;
}
.el-card {
  width: 480px;
  height: 320px;
  margin-top: 300px;
}
.el-button {
  width: 100%;
}
</style>

<style>
* {
  margin: 0px;
  padding: 0px;
}
</style>
